//
//  YQAFNetworkReachabilityTool.m
//  yiqiquan
//
//  Created by lx on 16/7/14.
//  Copyright © 2016年 honhot. All rights reserved.
//  AFN检测网络

#import "YQAFNetworkReachabilityTool.h"
#import <netinet/in.h>
#import <netinet6/in6.h>

@implementation YQAFNetworkReachabilityTool

XCYSharedInstanceM(Tool);

#pragma mark - 外部方法
//开始监控网络
- (void)startMonitoring
{
    AFNetworkReachabilityManager *rm = [AFNetworkReachabilityManager sharedManager];
    
    [rm setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //记录当前网络状态
        _status = status;
        _network = (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi);
    }];
    [rm startMonitoring];
}

//停止监控网络
- (void)stopMonitoring
{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

#pragma mark - 立刻获取网络状态
+ (BOOL)requestBeforeJudgeConnect
{
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
    struct sockaddr_in6 zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin6_len = sizeof(zeroAddress);
    zeroAddress.sin6_family = AF_INET6;
#else
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
#endif
    
    SCNetworkReachabilityRef defaultRouteReachability =
    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags =
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        printf("Error. Count not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;
    return isNetworkEnable;
}

@end
